//
//  HomeViewController.m
//  OrderFood
//
//  Created by xiaofang wang on 2018/10/22.
//  Copyright © 2018年 zhiyuan. All rights reserved.
//

#import "HomeViewController.h"
#import "BaseTabBarViewController.h"
#import "AppDelegate.h"
#import "LoginViewController.h"
#import "BaseNaviViewController.h"
#import "FinishOrderViewController.h"

//model
#import "HomeModel.h"


@interface HomeViewController () < SRWebSocketDelegate >

@property (strong, nonatomic)SRWebSocket *webSocket;
@property (strong, nonatomic)NSTimer *timerReConnect;
@property (strong, nonatomic)NSTimer *timerReSend;

/**头像Iv*/
@property (nonatomic, strong) UIImageView *iconIv;
/**姓名Lb*/
@property (nonatomic, strong) UILabel *nameLb;
/**工号Lb*/
@property (nonatomic, strong) UILabel *jobNumberLb;
/**今日收益*/
@property (nonatomic, strong) UILabel *salaryLb;
/**今日完成单数*/
@property (nonatomic, strong) UILabel *orderNumberLb;

@end

@implementation HomeViewController
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = WHITECOLOR;
    
    if (![USERDEFAULT boolForKey:LOGIN]) {
        LoginViewController *vc = [[LoginViewController alloc] init];
        BaseNaviViewController *navc = [[BaseNaviViewController alloc] initWithRootViewController:vc];
        [self presentViewController:navc animated:YES completion:nil];
    }
    
    [self setUI];
    
//    [self initSocket];
    
    [self loadHomeData];
}

-(void)socketReConnect {
    ////有网络情况下进行重链接
    if ([[RequestManager sharedManager] isConnectNetWork]) {
        [self initSocket];
    }
}


-(void)initSocket {
    
    __weak HomeViewController *weakSelf = self;
    weakSelf.webSocket.delegate = nil;
    [weakSelf.webSocket close];
    
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@/websocket/position/upload", BASE_URL]];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    
    // 先将dic转JSON
    NSString *jsonStr = [[RequestManager sharedManager] rb_jsonStrFromDic:@{@"event":@"UPLOAD_POSITION",@"data":@{@"latitude":@(12.7907), @"longitude":@(134.07976)}}];
    //时间戳 ：一定要传一样的。
    NSString *timeStampStr = [[RequestManager sharedManager] getNowTime];
    
    //如果有token就传，没有就传空
    NSString *token = TOKEN_VALUE;
    
    NSString *autoStr = [[RequestManager sharedManager] authorizationWithToken:token apiStr:@"/websocket/position/upload" timeStamp:timeStampStr];
    
    // ❌❌❌❌❌❌❌❌❌巨坑 如果有换行符：❌❌❌❌❌❌❌❌❌ 是设置不了请求头的
    NSString *shouquanStr = [[RequestManager sharedManager] pureStrWithOriginStr:autoStr]; //提纯
    
    
    [request setValue:shouquanStr forHTTPHeaderField:@"Authorization"];
    [request setValue:@"12345\n566" forHTTPHeaderField:@"test"]; //如果有换行,该请求头字段设置失败. 所以这句话谢了等于没写。
    
    [request setValue:@"1.0.0" forHTTPHeaderField:@"Authorization-Version"]; //版本
    [request setValue:timeStampStr forHTTPHeaderField:@"Authorization-Timestamp"]; //时间戳 需要和签名中的时间戳保持一致
    [request setValue:@"ios" forHTTPHeaderField:@"authorization-device"]; //设备
    
    [request setValue:@"zh-CN" forHTTPHeaderField:@"Accept-Language"]; //语言
    
    // 设置请求体: ⚠️❗️
    [request setHTTPBody:[jsonStr dataUsingEncoding:NSUTF8StringEncoding]];
    weakSelf.webSocket = [[SRWebSocket alloc] initWithURLRequest:request];
    weakSelf.webSocket.delegate = self;
    [weakSelf.webSocket open];
}



#pragma mark - 链接服务器成功
- (void)webSocketDidOpen:(SRWebSocket *)webSocket {
    ////清除重连定时器
    if (_timerReConnect) {
        [_timerReConnect invalidate];
        _timerReConnect = nil;
    }
    /////重复发送定位
    if (!_timerReSend) {
        _timerReSend = [NSTimer scheduledTimerWithTimeInterval:80 target:self selector:@selector(socketReSend) userInfo:nil repeats:YES];
    }
}


-(void)socketReSend {
    [self updateRiderLoction:self.webSocket];
}


#pragma mark - 断开链接 自动重连
-(void)webSocket:(SRWebSocket *)webSocket didFailWithError:(NSError *)error {
    
    ////清除定时器
    if (_timerReSend) {
        [_timerReSend invalidate];
        _timerReSend = nil;
    }
    
    ////50秒连一次 直到链接到
    if (!_timerReConnect) {
        _timerReConnect = [NSTimer scheduledTimerWithTimeInterval:50 target:self selector:@selector(socketReConnect) userInfo:nil repeats:YES];
    }

}


#pragma mark - 关闭连接
- (void)webSocket:(SRWebSocket *)webSocket didCloseWithCode:(NSInteger)code reason:(NSString *)reason wasClean:(BOOL)wasClean {
    [webSocket close];
    webSocket = nil;
    webSocket.delegate = nil;
    [_timerReSend invalidate];
    _timerReSend = nil;
    [_timerReConnect invalidate];
    _timerReConnect = nil;
}


#pragma mark - 上传成功位置信息后服务器不会返回数据 上传失败才会返回
- (void)webSocket:(SRWebSocket *)webSocket didReceiveMessage:(id)message  {
}


#pragma mark - 向服务器上传骑手的位置
-(void)updateRiderLoction:(SRWebSocket *)webSocket {
    [GetLocation getMoLocationWithSuccess:^(double lat, double lng) {
        NSString *jsonStr = [[RequestManager sharedManager] rb_jsonStrFromDic:@{@"event":@"UPLOAD_POSITION",@"data":@{@"latitude":@(lat), @"longitude":@(lng)}}];
        NSString *shouquanStr = [[RequestManager sharedManager] pureStrWithOriginStr:jsonStr];
        [webSocket send:shouquanStr];
    } Failure:^(NSError *error) {
    }];
}


-(void)setUI{
//骑手基本信息
    CGFloat topH = SCREEN_WIDTH*420/750;
    UIImageView *bgImgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, topH)];
    bgImgView.image = IMAGE(@"b");
    [self.view addSubview:bgImgView];
    
    
    
    
    NSDateFormatter*formatter = [[NSDateFormatter alloc]init];[formatter setDateFormat:@"yyy-MM-dd"];
    NSString*dateTime = [formatter stringFromDate:[NSDate date]];
    
    
    NSCalendar * calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; // 指定日历的算法
    NSDateComponents *comps = [calendar components:NSWeekdayCalendarUnit fromDate:[NSDate date]];
    NSNumber * weekNumber = @([comps weekday]);

    
    UILabel *timeLb = [[UILabel alloc] initWithFrame:CGRectMake(0, SafeArealanHeight, SCREEN_WIDTH, 50)];
    timeLb.font = FONT(15);
    timeLb.textColor = WHITECOLOR;
    timeLb.textAlignment = NSTextAlignmentCenter;
    timeLb.text = [NSString stringWithFormat:@"%@  %@", dateTime, [self returnWeekDay:[weekNumber integerValue]]];
    [bgImgView addSubview:timeLb];
    
    UIImageView *userImgView = [[UIImageView alloc] initWithFrame:CGRectMake(15, (topH-75)/2.0, 75, 75)];
    userImgView.layer.cornerRadius = GetHeight(userImgView)/2.0;
    userImgView.image = IMAGE(@"tx");
    self.iconIv = userImgView;
    [bgImgView addSubview:userImgView];
    
    UILabel *nameLb = [[UILabel alloc] initWithFrame:CGRectMake(GetMaxX(userImgView)+10, GetMinY(userImgView)+17, 200, 20)];
    nameLb.font = FONT(15);
    nameLb.textColor = WHITECOLOR;
    nameLb.text = @"张三";
    self.nameLb = nameLb;
    [bgImgView addSubview:nameLb];
    
    UILabel *jobNumberLb = [[UILabel alloc] initWithFrame:CGRectMake(GetMaxX(userImgView)+10, GetMaxY(nameLb), 200, 20)];
    jobNumberLb.font = FONT(15);
    jobNumberLb.textColor = WHITECOLOR;
    jobNumberLb.text = @"工号：251478";
    self.jobNumberLb = jobNumberLb;
    [bgImgView addSubview:jobNumberLb];
//骑手今日收益
    CGFloat midW = SCREEN_WIDTH-30;
    CGFloat midH = (SCREEN_WIDTH-30)*260/720;
    UIImageView *whiteImgView = [[UIImageView alloc] initWithFrame:CGRectMake(15, topH-41*KWidth_Scale, midW, midH)];
    whiteImgView.image = IMAGE(@"a");
    whiteImgView.userInteractionEnabled = YES;
    [self.view addSubview:whiteImgView];
    
    
    
    
    NSArray *topAry = @[@"今日完成单数",@"今日收益"];
    NSArray *dataAry = @[@"52",@"109"];
    
    for (int i = 0; i < 2; i++) {
        
        UILabel *topLb = [[UILabel alloc] initWithFrame:CGRectMake(midW/2*i, 35*KWidth_Scale, midW/2, 20)];
        topLb.font = FONT(15);
        topLb.textColor = RGBHex(0x999999);
        topLb.textAlignment = NSTextAlignmentCenter;
        topLb.text = topAry[i];
        [whiteImgView addSubview:topLb];
        
        UILabel *dataLb = [[UILabel alloc] initWithFrame:CGRectMake(midW/2*i, GetMaxY(topLb)+15, midW/2, 20)];
        dataLb.font = FONT(24);
        dataLb.textColor = BLACKCOLOR;
        dataLb.textAlignment = NSTextAlignmentCenter;
        dataLb.text = dataAry[i];
        [whiteImgView addSubview:dataLb];

        if (i==0) {
            self.orderNumberLb = dataLb;
        }else {
            self.salaryLb = dataLb;
        }

        UIView *backView = [[UIView alloc]initWithFrame:CGRectMake(midW/2*i, 0, midW/2, midH)];
        backView.backgroundColor = [UIColor clearColor];
        backView.userInteractionEnabled = YES;
        backView.tag = 155+i;
        [whiteImgView addSubview:backView];
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];
        [backView addGestureRecognizer:tap];
    }
    
    //开始接单 --> 配送地图
    UIButton *startBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    startBtn.backgroundColor = [UIColor rb_colorWithHex:0xE0916B]; //
    startBtn.frame = CGRectMake((SCREEN_WIDTH-150)/2, 60*KWidth_Scale+GetMaxY(whiteImgView), 150, 150);
    [startBtn setTitle:@"配送地图" forState:(UIControlStateNormal)];
    [startBtn setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
    [startBtn setTitleColor:[UIColor lightGrayColor] forState:(UIControlStateHighlighted)];
    [self.view addSubview:startBtn];
    [startBtn addTarget:self action:@selector(startWork) forControlEvents:UIControlEventTouchUpInside];
    
    startBtn.layer.cornerRadius=startBtn.frame.size.width/2;//裁成圆角
    startBtn.layer.masksToBounds=YES;//隐藏裁剪掉的部分
}


//更新页面数据
- (void)updateUIWithHomeModel:(HomeModel *)model {
    self.nameLb.text = model.name;
    self.jobNumberLb.text = [NSString stringWithFormat:@"工号:%@",model.riderId];
    NSURL *headurl = [NSURL URLWithString:[NSString stringWithFormat:@"%@",model.head]];
    [self.iconIv sd_setImageWithURL:headurl placeholderImage:[UIImage imageNamed:@"tx"]];
    self.orderNumberLb.text = [NSString stringWithFormat:@"%@",model.order];
    self.salaryLb.text = [NSString stringWithFormat:@"%@",model.salary];
}


-(void)tapAction:(UITapGestureRecognizer *)sender {
    if (sender.view.tag == 155) {//////点击的是今日完成的订单
        FinishOrderViewController *vc = [FinishOrderViewController new];
        vc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];
    }else {//////点击的是收益
        
    }
}




-(void)startWork{
    AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    UIWindow *mainWindow = appDelegate.window;
    BaseTabBarViewController *tabBarVC = (BaseTabBarViewController *)mainWindow.rootViewController;
    tabBarVC.selectedIndex = 1;
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    
    return UIStatusBarStyleLightContent;
    
}


-(NSString *)returnWeekDay:(NSInteger)weekDay {
    switch (weekDay) {
        case 1:
            return @"星期日";
            break;
        case 2:
            return @"星期一";
            break;
        case 3:
            return @"星期二";
            break;
        case 4:
            return @"星期三";
            break;
        case 5:
            return @"星期四";
            break;
        case 6:
            return @"星期五";
            break;
        case 7:
            return @"星期六";
            break;
    }
    return @"星期一";
}

#pragma mark - 网路请求
- (void)loadHomeData {

    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.backgroundColor = [UIColor rb_colorWithHex:0x666666 alpha:0.8];

    [NetWork requestHomeSuccessBlock:^(NSDictionary * _Nonnull response) {

        [hud hideAnimated:YES];
        
        if (RES_SUCESS) { //解析
            NSDictionary *dic = response[@"data"];
            HomeModel *model = [HomeModel mj_objectWithKeyValues:dic];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self updateUIWithHomeModel:model];
            });
            
        }else {
            [IndicatorManager showFailure:MESSAGE];
        }
    } failureBlock:^(NSString * _Nonnull message) {
        [IndicatorManager showFailure:message];
        
        [hud hideAnimated:YES];
    }];
}
@end
